package com.example.wengwyue.patientapplication.fragment;

import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.wengwyue.patientapplication.R;
import com.example.wengwyue.patientapplication.controller.ActivityController;
import com.example.wengwyue.patientapplication.network.UserApi;
import com.example.wengwyue.patientapplication.utils.ToastUtil;
import com.hospital.common.api.DataCallback;
import com.hospital.common.api.UserEntityKeeper;
import com.hospital.common.api.model.Error;
import com.hospital.common.api.model.UserKeeper;
import com.hospital.common.api.secure.AESKey;
import com.hospital.common.api.secure.SoftDog;
import com.hospital.common.ui.base.AbsFragment;
import com.hospital.common.util.InputMethodUtils;
import com.hospital.common.util.PatternUtil;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lingquan(quan.ling@hotmail.com) on 16/8/14.
 */
public class RegisterSetInfoFragment extends AbsFragment {
    String[] Actions = new String[]{
            "男", "女"
    };

    @Bind(R.id.reset_psw_editText)
    EditText mResetPswEditText;
    @Bind(R.id.psw_show_btn_1)
    ImageView mPswShowBtn1;
    @Bind(R.id.reset_psw_repeat_editText)
    EditText mResetPswRepeatEditText;
    @Bind(R.id.psw_show_btn_2)
    ImageView mPswShowBtn2;
    @Bind(R.id.register_user_name_editText)
    EditText mRegisterUserNameEditText;
    @Bind(R.id.register_card_id_editText)
    EditText mRegisterCardIdEditText;
    @Bind(R.id.user_gender_textView)
    TextView mUserGenderTextView;
    @Bind(R.id.user_gender_layout)
    RelativeLayout mUserGenderLayout;
    @Bind(R.id.user_age_textView)
    TextView mUserAgeTextView;
    @Bind(R.id.user_age_layout)
    RelativeLayout mUserAgeLayout;
    @Bind(R.id.verify_phone_textView)
    TextView mVerifyPhoneTextView;

    Drawable mEyeDrawable;
    Drawable mEyeOffDrawable;

    boolean isShowPassword1;
    boolean isShowPassword2;

    String mGender = null;
    int mAge = -1;

    String mPhone;
    AESKey mAESKey;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle arg = getArguments();
        mPhone = arg.getString("PHONE");
        mAESKey = arg.getParcelable("AESKEY");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register_set_info, null, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mEyeDrawable = ActivityCompat.getDrawable(getActivity(), R.mipmap.ic_eye);
        mEyeOffDrawable = ActivityCompat.getDrawable(getActivity(), R.mipmap.ic_eye_off);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.psw_show_btn_1, R.id.psw_show_btn_2, R.id.user_gender_textView, R.id.user_age_textView, R.id.verify_phone_textView})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.psw_show_btn_1:
                isShowPassword1 = !isShowPassword1;
                mResetPswEditText.setTransformationMethod(isShowPassword1 ? HideReturnsTransformationMethod.getInstance() :
                        PasswordTransformationMethod.getInstance());
                mResetPswEditText.setSelection(mResetPswEditText.getText().length());
                mPswShowBtn1.setImageDrawable(isShowPassword1 ? mEyeDrawable : mEyeOffDrawable);
                break;
            case R.id.psw_show_btn_2:
                isShowPassword2 = !isShowPassword2;
                mResetPswRepeatEditText.setTransformationMethod(isShowPassword2 ? HideReturnsTransformationMethod.getInstance() :
                        PasswordTransformationMethod.getInstance());
                mResetPswRepeatEditText.setSelection(mResetPswRepeatEditText.getText().length());
                mPswShowBtn2.setImageDrawable(isShowPassword2 ? mEyeDrawable : mEyeOffDrawable);
                break;
            case R.id.user_gender_textView:
                InputMethodUtils.closeKeybord(getActivity());

                int selectedPos = -1;
                if (!TextUtils.isEmpty(mGender)) {
                    selectedPos = Actions[0].equals(mGender) ? 0 : 1;
                }
                new MaterialDialog.Builder(getActivity())
                        .items(Actions)
                        .itemsCallbackSingleChoice(selectedPos, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                mGender = Actions[which];
                                mUserGenderTextView.setText(mGender);
                                return false;
                            }
                        })
                        .show();
                break;
            case R.id.user_age_textView:
                InputMethodUtils.closeKeybord(getActivity());

                View root = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_age_pick, null);
                final NumberPicker picker = (NumberPicker)root.findViewById(R.id.number_picker);
                picker.setMaxValue(150);
                picker.setMinValue(1);
                picker.setValue(mAge == -1 ? 20 : mAge);
                picker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);

                new MaterialDialog.Builder(getActivity())
                        .customView(root, false)
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mAge = picker.getValue();

                                mUserAgeTextView.setText(String.valueOf(mAge));
                            }
                        })
                        .show();
                break;
            case R.id.verify_phone_textView:
                commit();
                break;
        }
    }

    void commit() {
        if (!validateInput()) {
            return;
        }

        String digest = null;
        try {
            JSONObject obj = new JSONObject();
            obj.put("password", mResetPswEditText.getText().toString());
            obj.put("name", mRegisterUserNameEditText.getText().toString());
            obj.put("identity", mRegisterCardIdEditText.getText().toString());
            obj.put("phone", mPhone);
            obj.put("sex", mGender.equals("男"));
            obj.put("age", mAge);

            digest = SoftDog.encodeAES(obj.toString(), mAESKey.key, mAESKey.vi).replaceAll("\r|\n", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserApi.detailRegister(mPhone, mAESKey, digest, new DataCallback() {
            @Override
            public void onSuccess(Object data) {
                ToastUtil.show(getActivity(), "提交成功");

                UserKeeper keeper = new UserKeeper();
                keeper.key = mAESKey;
                keeper.name = mPhone;
                UserEntityKeeper.writeAccessToken(keeper);
                ActivityController.goToMain(getActivity());

                getActivity().finish();
            }

            @Override
            public void onFailed(Error error) {
                ToastUtil.show(getActivity(), error.des);
            }

        });
    }

    boolean validateInput() {
        if (TextUtils.isEmpty(mResetPswEditText.getText())
                || TextUtils.isEmpty(mResetPswRepeatEditText.getText())) {
            ToastUtil.show(getActivity(), "请输入密码");
            return false;
        }
        if (!mResetPswEditText.getText().toString().equals(mResetPswRepeatEditText.getText().toString())) {
            ToastUtil.show(getActivity(), "密码不一致");
            return false;
        }
        if (TextUtils.isEmpty(mRegisterUserNameEditText.getText())) {
            ToastUtil.show(getActivity(), "请输入用户名");
            return false;
        }
        if (TextUtils.isEmpty(mRegisterCardIdEditText.getText())) {
            ToastUtil.show(getActivity(), "请输入身份证号码");
            return false;
        }
        if (!PatternUtil.isIDCard(mRegisterCardIdEditText.getText().toString())) {
            ToastUtil.show(getActivity(), "请输入有效身份证号码");
            return false;
        }
        if (TextUtils.isEmpty(mGender)) {
            ToastUtil.show(getActivity(), "请选择性别");
            return false;
        }
        if (mAge == -1) {
            ToastUtil.show(getActivity(), "请选择年龄");
            return false;
        }
        return true;
    }
}
